package org.naxx.security.testng;

import org.apache.log4j.Logger;
import org.naxx.security.Main;
import org.naxx.security.api.Repository;
import org.naxx.security.api.impl.RepositoryImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * This class will initialize application context and call
 * <code>Main.setRepository()</code>.
 */
public class SpringContextAware {
	
	private static final Logger logger = Logger.getLogger(SpringContextAware.class);
	
	protected Repository repository;
	
	public void setUp() throws Exception {
		this.loadApplicationContext();
	}
	
	public void tearDown() throws Exception {
	}
	
	/**
	 * This method will make proper call to <code>Main.setRepository(ctx)</code>.
	 */
	private final void loadApplicationContext() {
		logger.debug("Loading Spring context from file '" + this.getContextFileNameOnClasspath() + "'");
		ApplicationContext context = new ClassPathXmlApplicationContext(this.getContextFileNameOnClasspath());
		logger.debug("Spring context successfully loaded from file '" + this.getContextFileNameOnClasspath() + "'");
		this.repository = new RepositoryImpl(context);
		Main.setRepository(this.repository);
	}
	
	/**
	 * Override if you want to load Spring from non-default context
	 * XML file. By default we search for file named <code>"test-applicationContext.xml"</code>
	 * in the root of classpath.
	 */
	protected String getContextFileNameOnClasspath() {
		return "test-applicationContext.xml";
	}
}
